# -*- coding: utf-8 -*-
import json
import logging

from PySide6.QtGui import QDoubleValidator
from PySide6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QHBoxLayout, \
    QLabel, QLineEdit, QPushButton, QMessageBox, QDialog, QComboBox
from PySide6.QtCore import Qt

from kumquat_king_pyside6.app_config import KUMQUAT_MANAGE_HEADER, ADD_KUMQUAT_COMBO, ADD_KUMQUAT_FORMAT_COMBO
from kumquat_king_pyside6.controls.apis import get_kumquats, create_kumquat
from kumquat_king_pyside6.tools import message_box, kumquat_format_converter


class KumquatManagePage(QWidget):
    def __init__(self):
        super().__init__()
        self.init_args()
        self.init_ui()
        self.init_slots()

    def init_args(self):
        self.kumquats = []
        code, kumquatsRes = get_kumquats()
        print(kumquatsRes)
        if code != 200:
            message_box("Error", "Failed to get kumquats")
            return
        self.kumquats = kumquatsRes[0]['data']
        logging.info(f"Get kumquat data {self.kumquats}")

    def init_ui(self):
        self.setObjectName("Kumquat_Manager_Page")
        layout = QVBoxLayout()
        manageLayout = QHBoxLayout()
        self.onlyCurrentCheckBox = QCheckBox("只显示目前市场价")
        self.onlyCurrentCheckBox.setChecked(True)
        self.addNewKumquatBtn = QPushButton("添加金桔价格")
        manageLayout.addWidget(self.onlyCurrentCheckBox)
        manageLayout.addWidget(self.addNewKumquatBtn)
        # 创建一个 QTableWidget
        self.table = QTableWidget()
        self.table.setColumnCount(6)  # 设置列数
        self.table.setHorizontalHeaderLabels(KUMQUAT_MANAGE_HEADER)  # 设置表头

        # 设置表格为可排序
        self.table.setSortingEnabled(True)

        # 设置表格为可滚动
        self.table.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        self.table.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)

        self.add_data_to_table()

        # 将表格添加到布局中
        layout.addLayout(manageLayout)
        layout.addWidget(self.table)

        # 设置布局
        self.setLayout(layout)

    def init_slots(self):
        self.onlyCurrentCheckBox.stateChanged.connect(self.add_data_to_table)
        self.addNewKumquatBtn.clicked.connect(self.add_new_kumquat)

    def add_data_to_table(self):
        self.table.setRowCount(0)
        filteredKumquats = [x for x in self.kumquats if x['note'] == 'CURRENT'] if \
            self.onlyCurrentCheckBox.isChecked() else self.kumquats
        rowCount = len(filteredKumquats)
        self.table.setRowCount(rowCount)
        # print(f"Row count {rowCount}")
        for row, data in enumerate(filteredKumquats):
            self.table.setItem(row, 0, QTableWidgetItem(data['name']))
            self.table.setItem(row, 1, QTableWidgetItem(kumquat_format_converter(data['style'], flag='ST2ZH')))
            self.table.setItem(row, 2, QTableWidgetItem(str(data['price'])))
            self.table.setItem(row, 3, QTableWidgetItem(str(data['original_price'])))
            self.table.setItem(row, 4, QTableWidgetItem(str(data['profit'])))
            self.table.setItem(row, 5, QTableWidgetItem(str(data['note'])))
            self.table.setItem(row, 6, QTableWidgetItem(str(data['note'])))

        # 调整列宽以适应内容，可拖拽
        self.table.resizeColumnsToContents()
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        header = self.table.horizontalHeader()
        header.setSectionsMovable(True)

    def add_new_kumquat(self):
        """
        弹出一个QWidget，添加新的金桔，有固定的下拉菜单金桔规格，数字lineEdit原价，市场价, 底部添加两个按钮，添加，取消
        :return:
        """
        self.addNewKumquatPage = AddKumquatPage()
        self.addNewKumquatPage.exec_()
        self.init_args()
        self.add_data_to_table()


class AddKumquatPage(QDialog):
    def __init__(self):
        super().__init__()
        self.init_args()
        self.init_ui()
        self.init_slots()

    def init_args(self):
        pass

    def init_slots(self):
        self.add_button.clicked.connect(self.on_add_clicked)
        self.cancel_button.clicked.connect(self.close)

    def init_ui(self):
        # 设置窗口标题
        self.setWindowTitle('管理金桔')
        self.resize(500, 500)
        # 设置布局
        layout = QVBoxLayout()

        # 规格下拉菜单
        self.kumquat_name_combo = QComboBox()
        self.kumquat_name_combo.setPlaceholderText('请输入金桔名称')
        self.kumquat_name_combo.setEditable(True)
        self.kumquat_name_combo.addItems(ADD_KUMQUAT_COMBO)

        self.kumquat_format_combo = QComboBox()
        self.kumquat_format_combo.setPlaceholderText('请输入金桔规格')
        self.kumquat_format_combo.setEditable(True)
        self.kumquat_format_combo.addItems(ADD_KUMQUAT_FORMAT_COMBO)

        # 原价输入框
        self.original_price_label = QLabel('原价:')
        self.original_price_edit = QLineEdit()
        self.original_price_edit.setPlaceholderText('请输入金桔原价')
        self.original_price_edit.setValidator(QDoubleValidator())

        # 市场价输入框
        self.market_price_label = QLabel('市场价:')
        self.market_price_edit = QLineEdit()
        self.market_price_edit.setPlaceholderText('请输入金桔市场价')
        self.market_price_edit.setValidator(QDoubleValidator())

        # 添加按钮
        self.add_button = QPushButton('添加')


        # 取消按钮
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.on_cancel_clicked)

        # 将控件添加到布局中
        layout.addWidget(self.kumquat_name_combo)
        layout.addWidget(self.kumquat_format_combo)
        layout.addWidget(self.original_price_label)
        layout.addWidget(self.original_price_edit)
        layout.addWidget(self.market_price_label)
        layout.addWidget(self.market_price_edit)
        layout.addWidget(self.add_button)
        layout.addWidget(self.cancel_button)

        # 设置主布局
        self.setLayout(layout)

    def on_add_clicked(self):
        spec = self.kumquat_name_combo.currentText() + ' ' + self.kumquat_format_combo.currentText()
        original_price = self.original_price_edit.text()
        market_price = self.market_price_edit.text()

        # 这里可以添加保存逻辑
        print(f"添加金桔: 规格={spec}, 原价={original_price}, 市场价={market_price}")
        kumquatJson = {
            "name": self.kumquat_name_combo.currentText(),
            "style": self.kumquat_format_combo.currentText(),
            "price": float(market_price),
            "original_price": float(original_price),
        }

        resCode, res = create_kumquat(json.dumps(kumquatJson, ensure_ascii=False))
        msBox = QMessageBox()
        if resCode in [200, 201]:
            msBox.setWindowTitle("添加金桔")
            msBox.setText(f"添加金桔成功!")
            msBox.setDefaultButton(QMessageBox.Save)
            msBox.exec()
        else:
            msBox.setWindowTitle("添加金桔")
            msBox.setText(f"添加金桔失败! {res}")
            msBox.setDefaultButton(QMessageBox.Save)
            msBox.exec()
        # 关闭窗口
        self.accept()

    def on_cancel_clicked(self):
        # 关闭窗口
        self.close()
#
# if __name__ == '__main__':
#     from PySide6.QtWidgets import QApplication
#     import sys
#
#     app = QApplication(sys.argv)
#
#     window = KumquatManagePage()
#     window.show()
#
#     sys.exit(app.exec())
